package com.kuafu.latte.transport.client;

import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class ConnectionListener implements ChannelFutureListener {

    private static final Logger logger = LoggerFactory.getLogger(ConnectionListener.class);

    private NettyClient client;

    public ConnectionListener(NettyClient client){
        this.client = client;
    }
    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (!channelFuture.isSuccess()) {
            if (channelFuture.cause() != null) {
                logger.error("connect failed" + channelFuture.cause().getMessage(), channelFuture.cause());
            }
            logger.error("connect failed, start reconnect");
            Thread.sleep(3000);
            client.doConnect();
        } else {
            // 关闭旧的连接
            Channel oldChannel = client.getChannel(); // copy reference
            if (oldChannel != null) {
                oldChannel.close();
            }
            client.setChannel(channelFuture.channel());
            synchronized(client){
                client.notifyAll();
            }
            logger.info("connect success");
        }
    }
}
